from fastapi import APIRouter, HTTPException, Depends
from typing import List, Optional
from datetime import datetime
import logging

from models.quote import QuoteData, ApiResponse, SubscribeRequest
from services.websocket_client import WebSocketManager

router = APIRouter(prefix="/api/quotes", tags=["quotes"])
logger = logging.getLogger(__name__)

# 全局WebSocket管理器实例
ws_manager: Optional[WebSocketManager] = None


def get_ws_manager() -> WebSocketManager:
    """获取WebSocket管理器实例"""
    global ws_manager
    if ws_manager is None:
        raise HTTPException(status_code=503, detail="WebSocket服务未启动")
    return ws_manager


def set_ws_manager(manager: WebSocketManager):
    """设置WebSocket管理器实例"""
    global ws_manager
    ws_manager = manager


@router.get("/", response_model=ApiResponse)
async def get_all_quotes(ws_mgr: WebSocketManager = Depends(get_ws_manager)):
    """获取所有行情数据"""
    try:
        quotes = ws_mgr.get_all_quotes()
        
        return ApiResponse(
            status="success",
            message=f"获取到 {len(quotes)} 条行情数据",
            data={"quotes": quotes, "count": len(quotes)}
        )
    except Exception as e:
        logger.error(f"获取所有行情数据失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{symbol}", response_model=ApiResponse)
async def get_quote(symbol: str, ws_mgr: WebSocketManager = Depends(get_ws_manager)):
    """获取指定股票的行情数据"""
    try:
        quote = ws_mgr.get_quote(symbol.upper())
        
        if quote is None:
            raise HTTPException(
                status_code=404, 
                detail=f"未找到股票 {symbol} 的行情数据"
            )
        
        return ApiResponse(
            status="success",
            message=f"获取股票 {symbol} 行情成功",
            data={"quote": quote}
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取股票 {symbol} 行情失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/subscribe", response_model=ApiResponse)
async def subscribe_quotes(
    request: SubscribeRequest, 
    ws_mgr: WebSocketManager = Depends(get_ws_manager)
):
    """订阅股票行情"""
    try:
        if not ws_mgr.is_connected():
            raise HTTPException(
                status_code=503, 
                detail="WebSocket连接未建立，无法订阅"
            )
        
        # 转换为大写
        symbols = [symbol.upper() for symbol in request.symbols]
        
        success = await ws_mgr.subscribe_symbols(symbols)
        
        if success:
            return ApiResponse(
                status="success",
                message=f"成功订阅 {len(symbols)} 只股票",
                data={"symbols": symbols}
            )
        else:
            raise HTTPException(
                status_code=500, 
                detail="订阅请求发送失败"
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"订阅股票行情失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/unsubscribe", response_model=ApiResponse)
async def unsubscribe_quotes(
    request: SubscribeRequest, 
    ws_mgr: WebSocketManager = Depends(get_ws_manager)
):
    """取消订阅股票行情"""
    try:
        if not ws_mgr.is_connected():
            raise HTTPException(
                status_code=503, 
                detail="WebSocket连接未建立，无法取消订阅"
            )
        
        # 转换为大写
        symbols = [symbol.upper() for symbol in request.symbols]
        
        success = await ws_mgr.unsubscribe_symbols(symbols)
        
        if success:
            return ApiResponse(
                status="success",
                message=f"成功取消订阅 {len(symbols)} 只股票",
                data={"symbols": symbols}
            )
        else:
            raise HTTPException(
                status_code=500, 
                detail="取消订阅请求发送失败"
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"取消订阅股票行情失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/symbols/list", response_model=ApiResponse)
async def get_available_symbols(ws_mgr: WebSocketManager = Depends(get_ws_manager)):
    """获取可用的股票代码列表"""
    try:
        quotes = ws_mgr.get_all_quotes()
        symbols = list(quotes.keys())
        
        return ApiResponse(
            status="success",
            message=f"获取到 {len(symbols)} 个可用股票代码",
            data={"symbols": symbols, "count": len(symbols)}
        )
    except Exception as e:
        logger.error(f"获取可用股票代码失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/status/connection", response_model=ApiResponse)
async def get_connection_status(ws_mgr: WebSocketManager = Depends(get_ws_manager)):
    """获取WebSocket连接状态"""
    try:
        is_connected = ws_mgr.is_connected()
        
        return ApiResponse(
            status="success",
            message="连接状态查询成功",
            data={
                "connected": is_connected,
                "backend_uri": ws_mgr.client.uri,
                "quote_count": len(ws_mgr.get_all_quotes())
            }
        )
    except Exception as e:
        logger.error(f"获取连接状态失败: {e}")
        raise HTTPException(status_code=500, detail=str(e)) 